package cn.topcodes.tcsf.admin.web.controller.impl;

import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Unicorn
 * @date 2018/6/25
 */
@Controller
@RequestMapping("/admin/file-system")
public class FileSystemController {

    @GetMapping("index")
    public String index() {
        return "admin/file-system/index";
    }

    @ResponseBody
    @GetMapping("list")
    public ApiResponseEntity list(
            @RequestParam(required = true) String folderPath
    ) {
        folderPath = folderPath.replaceAll("\\\\", "/");
        FileList fileList = new FileList();
        fileList.setFolderPath(folderPath);

        File folder = new File(folderPath);
        if(!folder.exists()) {
            return ApiResponseEntity.buildFailed("[" + folderPath + "]不存在");
        }else {
             if(!folder.isDirectory()) {
                 return ApiResponseEntity.buildFailed("[" + folderPath + "]不是一个目录");
             }else {
                 File[] subFiles = folder.listFiles();
                 List<FileInfo> fileInfos = new ArrayList<>();
                 for(File file  : subFiles) {
                     FileInfo fileInfo = new FileInfo();
                     fileInfo.setDirectory(file.isDirectory());
                     fileInfo.setFile(file.isFile());
                     fileInfo.setName(file.getName());
                     fileInfo.setPath(file.getPath());
                     fileInfo.setSize(file.length());
                     fileInfo.setLastModified(new Date(file.lastModified()));
                     fileInfos.add(fileInfo);
                 }
                 fileList.setList(fileInfos);
                 fileList.setTotal(fileInfos.size());
             }
        }
        return ApiResponseEntity.buildOK(fileList);
    }

    @ResponseBody
    @GetMapping("parent")
    public ApiResponseEntity parent(
            @RequestParam(required = true) String folderPath
    ) {
        folderPath = folderPath.replaceAll("\\\\", "/");
        File file = new File(folderPath);
        if(!file.exists()) {
            return ApiResponseEntity.buildFailed("[" + folderPath + "]不存在");
        }
        File parentFile = file.getParentFile();
        if(!parentFile.exists() || !parentFile.isDirectory()) {
            return ApiResponseEntity.buildFailed("上级不存在");
        }
        return list(parentFile.getPath());
    }

    @ResponseBody
    @GetMapping("delete")
    public ApiResponseEntity delete(
            @RequestParam(required = true) String filePath
    ) {
        filePath = filePath.replaceAll("\\\\", "/");
        File file = new File(filePath);
        if(!file.exists()) {
            return ApiResponseEntity.buildFailed("[" + filePath + "]不存在");
        }
        boolean success = file.delete();
        if(success) {
            return ApiResponseEntity.buildOK(filePath + "删除成功");
        }else {
            return ApiResponseEntity.buildFailed("[" + filePath + "]删除失败");
        }
    }

    @ResponseBody
    @GetMapping("tomcat-logs")
    public ApiResponseEntity tomcatLogs() {
        String catalinaBase = System.getProperty("catalina.base");
        String folder = catalinaBase + "/logs";
        return list(folder);
    }

    @ResponseBody
    @GetMapping("get")
    public void file(
            @RequestParam(required = true) String filePath,
            HttpServletResponse response
    ) throws IOException {
        filePath = filePath.replaceAll("\\\\", "/");
        File file = new File(filePath);
        if(!file.exists() || !file.isFile()) {
            response.sendError(404);
            return;
        }
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor(filePath);
        response.setHeader("Content-Type", contentType + ";UTF-8");
        FileUtils.copyFile(file, response.getOutputStream());
    }
}

@Data
class FileList {

    private List<FileInfo> list;

    private int total;

    private String folderPath;
}

@Data
class FileInfo {

    private String name;

    private String path;

    private long size;

    private boolean isFile;

    private boolean isDirectory;

    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date lastModified;
}